package org.easy.core.util;


/**
 * 每秒支持生成4096个id
 * 移除机房id
 */
public class SnowflakeGenerator {

    private final long twepoch = 1725601039000L;

    // 机器id所占的位数
    private final long workerIdBits = 5L;
    // 支持的最大机器id，结果是31 (5位二进制数)
    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
    // 序列在id中占的位数
    private final long sequenceBits = 12L;
    // 机器ID向左移12位
    private final long workerIdShift = sequenceBits;
    // 时间截向左移17位(5+12)
    private final long timestampLeftShift = sequenceBits + workerIdBits;
    // 生成序列的掩码，这里为4095 (0b111111111111=0xfff)
    private final long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long workerId;
    private long sequence = 0L;
    private long lastTimestamp = -1L;

    public SnowflakeGenerator(long workerId) {
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }
        this.workerId = workerId;

    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();

        // 如果当前时间小于上一次ID生成的时间戳，说明系统时钟回退过，这时候应当抛出异常
        if (timestamp < lastTimestamp) {
            throw new RuntimeException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }

        // 如果是同一时间生成的，则进行毫秒内序列
        if (lastTimestamp == timestamp) {
            sequence = (sequence + 1) & sequenceMask;
            // 毫秒内序列溢出
            if (sequence == 0) {
                // 阻塞到下一个毫秒,获得新的时间戳
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            // 时间戳改变，毫秒内序列重置
            sequence = 0L;
        }

        // 上次生成ID的时间截
        lastTimestamp = timestamp;

        // 移位并通过或运算拼到一起组成64位的ID
        return ((timestamp - twepoch) << timestampLeftShift) | (workerId << workerIdShift) | sequence;
    }

    public static void main(String[] args) {
        long x = System.currentTimeMillis() - 1725601039000L;
        System.out.println(Long.toBinaryString(x) + "-" + Long.toBinaryString(x).length());
        System.out.println(Long.toBinaryString(x << 17) + "-" + Long.toBinaryString(x << 17).length());
        System.out.println(Long.toBinaryString(1 << 5) + "-" + Long.toBinaryString(1 << 5).length());

    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }


}
